<template>
  <div>
    <!-- 表单弹窗 -->
    <el-dialog
      class="el-dialog__wrapper avue-dialog avue-crud__dialog"
      :title="dialogText"
      :visible.sync="dialogVisible"
      append-to-body
      :close-on-click-modal="false"
      :before-close="handleClose"
      width="70%"
    >
      <el-form
        ref="form"
        :model="reprecForm"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="分账模式" prop="divisionPattern">
              <select-dict
                ref="divisionPattern"
                :select.sync="reprecForm.divisionPattern"
                code="division_pattern_hand"
                placeholder-text="分账模式"
                :disabled="dpDisabled"
                @change="handleDpChange"
              ></select-dict>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="reprecForm.divisionPattern">
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click.stop="handleReprecAdd"
              >新增分账方</el-button
            >
          </el-col>
        </el-row>
        <div class="alter-basic" v-if="reprecInfo.k2.length > 0">
          <div class="row-alter alter-width-4x">
            <div class="col-alter border-bottom">
              <span class="alter-title">结算对象</span>
            </div>
            <div
              class="col-alter"
              v-for="(k1Item, k1i) in reprecInfo.k1"
              :key="k1i"
            >
              {{ k1Item == 1 ? "分账方" : "接收方" }}
            </div>
          </div>
          <div class="row-alter alter-width-4x">
            <div class="col-alter border-bottom">
              <span class="alter-title">分账接收方编号</span>
            </div>
            <div
              class="col-alter"
              v-for="(k2Item, k2i) in reprecInfo.k2"
              :key="k2i"
            >
              {{ k2Item }}
            </div>
          </div>
          <div class="row-alter alter-width-4x">
            <div class="col-alter border-bottom">
              <span class="alter-title">分账接收方名称</span>
            </div>
            <div
              class="col-alter"
              v-for="(k3Item, k3i) in reprecInfo.k3"
              :key="k3i"
            >
              {{ k3Item }}
            </div>
          </div>
          <div class="row-alter alter-width-4x">
            <div class="col-alter border-bottom">
              <span class="alter-title">分账计算规则</span>
            </div>
            <div
              class="col-alter"
              v-for="(k4Item, k4i) in reprecInfo.k4"
              :key="k4i"
            >
              {{ k4Item == 1 ? "按比例分账" : k4Item == 2 ? "按金额分账" : "" }}
            </div>
          </div>
          <div class="row-alter alter-width-4x">
            <div class="col-alter border-bottom">
              <span class="alter-title">分账数值</span>
            </div>
            <div
              class="col-alter cols"
              v-for="(item, i) in reprecForm.divisionRateList"
              :key="i"
            >
              <el-form-item
                label=""
                label-width="0"
                :prop="'divisionRateList.' + i + '.value'"
                :rules="{
                  required: true,
                  message: '分账数值不能为空',
                  trigger: 'blur',
                }"
              >
                <el-input
                  type="number"
                  oninput="if(value){value=value.replace(/[^\d]/g,1);if(Number(value)<=0){value=0}} if(Number(value)>100){value=100}"
                  size="mini"
                  class="haruyuki-width-100"
                  placeholder="请输入0-100范围的值，总和为100"
                  v-model="item.value"
                  v-if="reprecForm.divisionPattern == 1"
                >
                  <span slot="suffix">%</span>
                </el-input>
                <el-input
                  type="number"
                  oninput="if(value){value=value.replace(/[^\d]/g,1);if(Number(value)<=0){value=0}} if(Number(value)>parseFloat(this.rptAmount)){value=parseFloat(this.rptAmount)}"
                  size="mini"
                  class="haruyuki-width-100"
                  :placeholder="'请输入总和为'+rptAmount+'元'"
                  v-model="item.value"
                  v-else-if="reprecForm.divisionPattern == 2"
                >
                  <span slot="suffix">元</span>
                </el-input>
              </el-form-item>
            </div>
          </div>
          <div class="row-alter alter-width-4x">
            <div class="col-alter border-bottom">
              <span class="alter-title">是否承担手续费</span>
            </div>
            <div
              class="col-alter cols"
              v-for="(item, i) in reprecForm.isChargeList"
              :key="i"
            >
              <el-form-item
                label=""
                label-width="0"
                :prop="'isChargeList.' + i + '.value'"
                :rules="{
                  required: true,
                  message: '是否承担手续费不能为空',
                  trigger: 'blur',
                }"
              >
                <el-radio
                  v-model="item.value"
                  :label="1"
                  @input="isSelectChange($event, i)"
                  >{{ "" }}</el-radio
                >
                <!-- <select-dict
                  ref="isCharge"
                  :select.sync="item.value"
                  code="is_charge"
                  placeholder-text="是否承担手续费"
                  @change="isSelectChange"
                ></select-dict> -->
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <span
        slot="footer"
        class="avue-dialog__footer avue-dialog__footer--right"
      >
        <el-button
          size="small"
          type="primary"
          v-preventClick
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
      </span>
      <!-- 表单弹窗 -->
      <el-dialog
        class="el-dialog__wrapper avue-dialog avue-crud__dialog"
        :title="'分账接收方'"
        :visible.sync="dialogChildVisible"
        append-to-body
        :close-on-click-modal="false"
        :before-close="handleChildClose"
      >
        <receive-table
          ref="receiveTable"
          :project-code="projectCode"
          v-if="dialogChildVisible"
        ></receive-table>
        <span
          slot="footer"
          class="avue-dialog__footer avue-dialog__footer--right"
        >
          <el-button
            size="small"
            type="primary"
            v-preventClick
            @click="handleChildSubmit"
            >确 定</el-button
          >
          <el-button size="small" @click="dialogChildVisible = false"
            >取 消</el-button
          >
        </span>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import {
  handDivRegist,
} from "@/api/rb-oem/separateMerchant/separate_merchant_store";
import selectPage from "@/components/select-page/select-page";
import selectDict from "@/components/select-dict/select-dict";
import receiveTable from "@/views/rb-oem/separateMerchant/components/receive-table";
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    projectCode: {
      type: String,
      default: "",
    },
    reprecInfo: {
      type: Object,
      default: () => ({
        data: {},
        k1: [],
        k2: [],
        k3: [],
        k4: [],
      }),
    },
    rptAmount: {
      type: [Number, String],
      default: 0,
    }
  },
  data() {
    return {
      dialogType: "",
      dialogText: "订单分账",
      reprecForm: {
        rptOrderCode: "",
        divisionPattern: "",
        divisionRateList: [],
        isChargeList: [],
        bindList: [],
      },
      rules: {
        divisionPattern: [
          { required: true, message: "请选择分账模式", trigger: "change" },
        ],
        divisionRule: [
          { required: true, message: "请选择分账规则", trigger: "change" },
        ],
      },
      dpDisabled: false,
      dialogChildVisible: false,
    };
  },
  watch: {
    
  },
  components: {
    selectPage,
    selectDict,
    receiveTable,
  },
  methods: {
    handleDpChange(val) {
      if (val) {
        this.refreshReset();
      }
    },
    isSelectChange(val, i) {
      for (const item of this.reprecForm.isChargeList) {
        item.value = 0;
      }
      this.reprecForm.isChargeList[i].value = val;
    },
    /* 新增分账方 */
    handleReprecAdd() {
      this.dialogChildVisible = true;
    },
    handleSubmit() {
      const _this = this;
      _this.$refs.form.validate((valid) => {
        if (valid) {
          _this.reprecForm.rptOrderCode = _this.reprecInfo.data.rptOrderCode;
          if (_this.reprecForm.divisionPattern == 1) {
            const divisionRateTotal = _this.reprecForm.divisionRateList.reduce(
              (acc, curr) => Number(acc) + Number(curr.value),
              0
            );
            if (divisionRateTotal !== 100) {
              _this.$message.warning("分账比例总和必须为100%");
              return;
            } else {
              // 清空绑定列表
              _this.reprecForm.bindList = [];
              // 直接遍历分账接收方数组，将每个接收方与对应的分账比例关联
              for (let index = 0; index < _this.reprecInfo.k2.length; index++) {
                _this.reprecForm.bindList.push({
                  rpiNo: _this.reprecInfo.k2[index],
                  divisionUserType: index === 0 ? 1 : 2, // 第一个为分账方，其余为接收方
                  divisionRate: _this.reprecForm.divisionRateList[index].value,
                  isCharge: _this.reprecForm.isChargeList[index].value,
                });
              }
              _this.$nextTick(() => {
                const loading = _this.$loading({
                  lock: true,
                  text: "提交中...",
                  spinner: "el-icon-loading",
                });
                handDivRegist(_this.reprecForm)
                  .then(() => {
                    _this.$message.success("操作成功");
                    _this.dialogVisible = false;
                    _this.refreshReset();
                    _this.refreshChange();
                  })
                  .finally(() => {
                    loading.close();
                  });
              });
            }
          } else {
            const divisionRateTotal = _this.reprecForm.divisionRateList.reduce(
              (acc, curr) => Number(acc) + Number(curr.value),
              0
            );
            if (divisionRateTotal !== Number(_this.rptAmount)) {
              _this.$message.warning("分账比例总和必须为"+_this.rptAmount+"元");
              return;
            } else {
              // 清空绑定列表
              _this.reprecForm.bindList = [];
              // 直接遍历分账接收方数组，将每个接收方与对应的分账比例关联
              for (let index = 0; index < _this.reprecInfo.k2.length; index++) {
                _this.reprecForm.bindList.push({
                  rpiNo: _this.reprecInfo.k2[index],
                  divisionUserType: index === 0 ? 1 : 2, // 第一个为分账方，其余为接收方
                  divisionAmont: _this.reprecForm.divisionRateList[index].value,
                  isCharge: _this.reprecForm.isChargeList[index].value,
                });
              }
              _this.$nextTick(() => {
                const loading = _this.$loading({
                  lock: true,
                  text: "提交中...",
                  spinner: "el-icon-loading",
                });
                handDivRegist(_this.reprecForm)
                  .then(() => {
                    _this.$message.success("操作成功");
                    _this.dialogVisible = false;
                    _this.refreshReset();
                    _this.refreshChange();
                  })
                  .finally(() => {
                    loading.close();
                  });
              });
            }
          }
        }
      });
    },
    handleClose(done) {
      this.$refs.form.resetFields();
      this.refreshReset();
      done();
    },
    refreshReset() {
      this.reprecInfo.k1 = [];
      this.reprecInfo.k2 = [];
      this.reprecInfo.k3 = [];
      this.reprecInfo.k4 = [];
      this.reprecForm.divisionRateList = [];
      this.reprecForm.isChargeList = [];
    },
    handleChildSubmit() {
      if (this.$refs["receiveTable"].selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      } else {
        let list = this.$refs["receiveTable"].selectionList;

        // 如果已有分账接收方，需要过滤掉重复的
        if (this.reprecInfo.k2.length > 0) {
          // 获取已存在的分账接收方编号
          const existingRpiNos = new Set(this.reprecInfo.k2);

          // 过滤出不重复的分账接收方
          const newItems = list.filter(
            (item) => !existingRpiNos.has(item.rpiNo)
          );

          // 添加新的分账接收方
          for (const item of newItems) {
            this.reprecInfo.k1.push(2);
            this.reprecInfo.k2.push(item.rpiNo);
            this.reprecInfo.k3.push(item.rpiName);
            this.reprecInfo.k4.push(this.reprecForm.divisionPattern);
            this.reprecForm.divisionRateList.push({ value: null });
            this.reprecForm.isChargeList.push({ value: 0 });
          }
        } else {
          this.reprecInfo.k1.push(1);
          this.reprecInfo.k2.push(this.reprecInfo.data.rpiNo);
          this.reprecInfo.k3.push(this.reprecInfo.data.rpiName);
          this.reprecInfo.k4.push(this.reprecForm.divisionPattern);
          this.reprecForm.divisionRateList.push({ value: null });
          this.reprecForm.isChargeList.push({ value: 0 });
          // 如果没有已存在的分账接收方，直接添加所有选中的
          for (const item of list) {
            this.reprecInfo.k1.push(2);
            this.reprecInfo.k2.push(item.rpiNo);
            this.reprecInfo.k3.push(item.rpiName);
            this.reprecInfo.k4.push(this.reprecForm.divisionPattern);
            this.reprecForm.divisionRateList.push({ value: null });
            this.reprecForm.isChargeList.push({ value: 0 });
          }
        }

        this.$message({
          type: "success",
          message: "添加成功!",
        });
        this.dialogChildVisible = false;
      }
    },
    handleChildClose(done) {
      done();
    },
  },
};
</script>

<style lang="scss" scoped>
.alter-basic {
  display: grid;
  grid-template-columns: repeat(6, 16.66%);
  border: 1px solid #ebeef5;

  .alter-title {
    font-weight: bold;
    color: rgba(0, 0, 0, 0.85);
  }
}

.row-alter {
  display: flex;
  flex-direction: column;
  &.alter-width-4x {
  }
  &:nth-child(n + 2) {
    border-left: 1px solid #ebeef5;
  }
}

.col-alter {
  padding-left: 10px;
  padding-right: 10px;
  line-height: 60px;
  height: 60px;
  // margin-bottom: 6px;
  font-size: 13px;
  &:nth-child(2) {
    color: #3f4c6b;
    // font-weight: bold;
  }
  &:nth-child(n + 3) {
    border-top: 1px solid #ebeef5;
  }
  &.border-bottom {
    border-bottom: 1px solid #ebeef5;
    word-break: break-word;
    background-color: #fafafa;
  }
  &.margin-top {
    margin-top: 6px;
  }
  &.margin-bottom {
    margin-bottom: 6px;
  }
}
.cols div:first-child:before {
  margin-top: 6px;
}

/deep/ .el-form-item__error {
  padding-top: 0;
}
</style>